package services

import (
	"encoding/json"
	"fmt"
	"github.com/jinzhu/gorm"
	"go_motor_catalog/dao"
	"go_motor_catalog/util"
	"strings"
)

const getCfmotoCatalogUrl = "https://www.cfmoto.com/active/ajax_call/get_article_list.html"

type CfmotoOm struct {
}

type CfmotoOmRes struct {
	ModelName       string
	ModelYear       string
	CatalogUrl      string
	CatalogShareUrl string
	Desc            string
}

func NewCfmotoOm() *CfmotoOm {
	return &CfmotoOm{}
}

func (c *CfmotoOm) getCatalog() []*CfmotoOmRes {
	res := make([]*CfmotoOmRes, 0)
	ccSlice := []string{"125cc", "150cc", "250cc", "400cc", "650cc", "700cc", "800cc", "1250cc"}
	for i := range ccSlice {
		ccName := ccSlice[i]
		param := map[string]string{
			"func_params[]": ccName,
		}
		body := util.NewHttpUtil().PostFormResty(getCfmotoCatalogUrl, param).Body()
		var dataList []map[string]string
		var resultApi map[string]interface{}
		var resultData map[string]interface{}
		err := json.Unmarshal(body, &resultApi)
		if err != nil {
			fmt.Println("获取春风图纸错误", err)
			return nil
		}
		marshal, err := json.Marshal(resultApi["res"])
		if err != nil {
			fmt.Println("获取春风图纸错误", err)
			return nil
		}
		err = json.Unmarshal(marshal, &resultData)
		if err != nil {
			fmt.Println("获取春风图纸错误", err)
			return nil
		}
		dataListByte, err := json.Marshal(resultData["res"])
		if err != nil {
			fmt.Println("获取春风图纸错误", err)
			return nil
		}
		err = json.Unmarshal(dataListByte, &dataList)
		if err != nil {
			fmt.Println("获取春风图纸错误", err)
			return nil
		}
		for m := range dataList {
			modelInfo := dataList[m]
			modelName := strings.Split(strings.ReplaceAll(fmt.Sprint(modelInfo["art_title"]), "\\", ""), " ")[0]
			modelYear := strings.Split(strings.ReplaceAll(fmt.Sprint(modelInfo["art_dateline"]), "\\", ""), "-")[0]
			catalogUrl := strings.ReplaceAll(fmt.Sprint(modelInfo["art_file"]), "\\", "")
			res = append(res, &CfmotoOmRes{
				ModelName:  modelName,
				ModelYear:  modelYear,
				CatalogUrl: catalogUrl,
			})
		}
	}
	return res
}

func (c *CfmotoOm) CrawData(db *gorm.DB) {
	catalogs := c.getCatalog()
	modelOmDao := dao.NewManualModelOmDao(db)
	catalogOmDao := dao.NewManualCatalogOmDao(db)
	for i := range catalogs {
		param := catalogs[i]
		modelParam := &dao.ManualModelOm{
			ModelName: param.ModelName,
			ModelYear: param.ModelYear,
			BrandId:   7,
		}
		catalogParam := &dao.ManualCatalogOm{
			CatalogUrl:  param.CatalogUrl,
			CatalogDesc: "",
		}
		modelId := modelOmDao.CreateManualModelOm(modelParam)
		catalogParam.ModelId = modelId
		catalogOmDao.CreateManualCatalogOm(catalogParam)
		fmt.Println(param.ModelName, "-", param.ModelYear, "-successfull")
	}
	fmt.Print("all successfull")
}
